﻿// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "Subsystem/ProtocolSubsystem.h"
#include "GameVersionSubsystem.generated.h"

UCLASS()
class MISCELLANEOUSPROJECT_API UGameVersionSubsystem : public UGameInstanceSubsystem 
{
	GENERATED_BODY()
public:
	virtual bool ShouldCreateSubsystem(UObject* Outer) const override { return true; }
	virtual void Initialize(FSubsystemCollectionBase& Collection) override;
	
public:
	void UpdateVersion(FString PakPath);
	FOnFilesDownloaderProgress& OnPakDownloadingProcess() { return PakDownloadingProcess; }
	FOnFilesDownloaderResult& OnOnePakDownloadComplete() { return PakOneDownloadComplete; }
	FOnFilesDownloaderResult& OnAllPakDownloadComplete() { return PakAllDownloadComplete; }

	void MountPak(TArray<FString> PakPaths=TArray<FString>());

	UFUNCTION(BlueprintCallable,Category = "GameVersionSubsystem")
	TArray<FString> GetServerVersionInfo()
	{
		TArray<FString> temp;
		ServerVersionInfo.PatchList.GenerateKeyArray(temp);
		return temp;
	}

	UFUNCTION(BlueprintCallable,Category = "GameVersionSubsystem")
    TArray<FString> GetClientVersionInfo()
	{
		TArray<FString> temp;
		ClientVersionInfo.PatchList.GenerateKeyArray(temp);
        return temp;
	}

	UFUNCTION(BlueprintCallable,Category = "GameVersionSubsystem")
    FString GetClientVersionPath()
	{
		return ClientVersionPath;
	}

	UFUNCTION(BlueprintCallable,Category = "GameVersionSubsystem")
    FString GetClientPakPath()
	{
		return ClientPakPath;
	}
	
	
private:
	FString ParseUrl(const FString& Content);
	TArray<FString> ParseSuportVersion(const FString& Content);
	TArray<FString> ParseExistVersion(const FString& Content);
	TMap<FString, FString> ParseServerExistPatch(const FString& Content);
	TMap<FString, FString> ParseClientExistPatch(const FString& Content);
	void GetServerVersionContent();
	void GetClientVersionContent();
	void CompareVersion();
	void OnPakDownloadingProcessDelegate(const int32 BytesSent, const int32 BytesReceived, const int32 FullSize);
	void OnOnePakDownLoaded(TEnumAsByte<DownloadResult> Result);
	void OnAllPakDownLoaded(TEnumAsByte<DownloadResult> Result);
	void DownloadPakFile(TArray<FString> FilePath, int32 currentIndex = 0);
	void DeletePakFile();
	void UpdateClientVersionContent();

	struct FVersionInfo
	{
		FString VersionContent;
		FString url;
		TArray<FString> SuportVersion;
		TArray<FString> VersionList;
		TMap<FString, FString> PatchList;
	};
	FVersionInfo ServerVersionInfo;
	FVersionInfo ClientVersionInfo;
	UProtocolSubsystem* ProtocolSubsystem;
	FString ServerVersionPath;
	FString ServerPakPath;
	FString ClientVersionPath;
	FString ClientPakPath;
	TArray<FString> NeedDownFiles, NeedDelFiles;
	FOnFilesDownloaderProgress PakDownloadingProcess;
	FOnFilesDownloaderResult PakOneDownloadComplete;
	FOnFilesDownloaderResult PakAllDownloadComplete;
	TArray<FString> NeedDownloadPakNames;
	int32 CurrentIndex;
};
